<template>
  <div>
    <el-dialog title="修改角色权限" :visible="dialogVisible" @close="close">
      <el-tree ref="tree" :data="treePerms" show-checkbox node-key="id"></el-tree>
      <div slot="footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getAllPerms } from "@/api/role";
import { editRole } from "@/api/role";
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  computed: {
    permids() {}
  },
  watch: {
    data() {
      //已有权限
      let permids = [];
      if (this.data && this.data.permids) {
        permids = this.data.permids
          .split(",")
          .filter(e => {
            return e && this.parentNodeIds.indexOf(Number.parseInt(e)) == -1;
          })
          .map(e => {
            return Number.parseInt(e);
          });
      }
      setTimeout(() => {
        this.$refs.tree.setCheckedKeys(permids);
      }, 0);
    }
  },
  data() {
    return {
      treePerms: [], //全部权限
      parentNodeIds: [] //所有父节点id，后面设置checkedNodes时候排除掉，避免用户没有勾选某子节点却被显示为勾选的情况
    };
  },
  created() {
    this.getAllPerms();
  },
  methods: {
    close() {
      this.$emit("update:dialogVisible", false);
    },
    async getAllPerms() {
      let r = await getAllPerms();
      if (r && r.error != 0) {
        this.$message({
          message: "获取权限数据失败",
          type: "error"
        });
        return;
      }
      this.treePerms = this.flat2tree(r.data);
      this.treePerms.splice(0, 0);
      this.findParentNodeIds(this.treePerms, this.parentNodeIds);
      console.log(this.parentNodeIds);
    },
    //获取所有父节点id，后面设置checkedNodes时候排除掉，避免用户没有勾选某子节点却被显示为勾选的情况
    findParentNodeIds(perms, parentNodeIds) {
      for (let i = 0; i < perms.length; i++) {
        if (perms[i].children && perms[i].children.length > 0) {
          parentNodeIds.push(perms[i].id);
          this.findParentNodeIds(perms[i].children, parentNodeIds);
        }
      }
    },
    //将服务器返回的权限数组转化为父子包含树
    flat2tree(flatLs) {
      let tree = [];
      flatLs.forEach(item => {
        item.label = item.name;
        if (item.pId === 0) {
          tree.push(item);
        } else {
          var index = flatLs.findIndex(item1 => item1.id === item.pId);
          if (index !== -1) {
            flatLs[index].children = flatLs[index].children || [];
            flatLs[index].children.push(item);
          }
        }
      });
      return flatLs.filter(item => item.pId === 0);
    },
    async save() {
      let permids = this.$refs.tree.getCheckedKeys();
      permids.push(...this.$refs.tree.getHalfCheckedKeys());
      this.data.perms = permids.join(",");
      let r = await editRole(this.data);
      if (r.error == 0) {
        this.close();
        this.$emit("finish");
      } else {
        this.$message({
          message: "出错了",
          type: "error"
        });
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.el-form-item {
  display: flex;
}
.el-form-item__content {
  flex: 1;
}
.el-select {
  flex: 1;
}
</style>